package ils.web.servlets;

import ils.di.ObjectBuilder;
import ils.di.ObjectBuilderFactory;
import ils.domain.model.User;
import ils.domain.model.UserRepository;
import ils.services.AuthenticationService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author: Rejeev Divakaran
 * Date: 7/20/13
 */
@WebServlet("/authentication/login")
public class LoginServlet extends HttpServlet {
    private UserRepository userRepository;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String targetUri = request.getParameter("targetUri");
        String sessionId = session.getId();
        if(AuthenticationService.authenticate(username, password, sessionId)){
            int userId = Integer.parseInt(username);
            User user = userRepository.getUser(userId);
            session.setAttribute("user", user);
            String userName = user.getFirstName();
            if(userName == null) userName = user.getLastName();
            if(userName == null) userName = username;
            session.setAttribute("username", userName);
            if(targetUri != null) response.sendRedirect(targetUri);
            else response.sendRedirect("/home");
        }else {
            request.setAttribute("message", "Login Failed");
            request.getRequestDispatcher("/authentication/login.jsp").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String targetUri = request.getParameter("targetUri");
        request.getRequestDispatcher("/authentication/login.jsp").forward(request, response);
    }

    @Override
    public void init(){
        ObjectBuilder objectBuilder = ObjectBuilderFactory.get();
        userRepository = objectBuilder.getInstance(UserRepository.class, true);
    }
}
